package com.itboye.eweilisten.me.personal.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.eweilisten.R;
import com.itboye.eweilisten.adapter.GirlGridAdapter;
import com.itboye.eweilisten.adapter.HeadGridAdapter;
import com.itboye.eweilisten.adapter.OldAdapter;
import com.itboye.eweilisten.adapter.XueShengAdapter;
import com.itboye.eweilisten.adapter.XueXiaoAdapter;
import com.itboye.eweilisten.app.MyApplication;
import com.itboye.eweilisten.base.BaseActivity;
import com.itboye.eweilisten.me.login.LoginActivity;
import com.itboye.eweilisten.me.personal.model.PersonDataBean;
import com.itboye.eweilisten.me.personal.myinterface.SelectAddressDialog;
import com.itboye.eweilisten.model.AddressBean;
import com.itboye.eweilisten.model.OldBean;
import com.itboye.eweilisten.model.QuestionBean;
import com.itboye.eweilisten.presenter.UserPresenter;
import com.itboye.eweilisten.util.address.AddressFragment;
import com.itboye.eweilisten.util.loadingutil.MAlert;
import com.itboye.eweilisten.util.sputil.Const;
import com.itboye.eweilisten.util.sputil.HeadUrl;
import com.itboye.eweilisten.util.sputil.SPUtils;
import com.itboye.eweilisten.util.widget.CameraPopupWindow;
import com.itboye.eweilisten.util.widget.CircleImageView;
import com.itboye.eweilisten.util.widget.FilterUtil;
import com.itboye.eweilisten.util.widget.HeadDialogs;
import com.itboye.eweilisten.util.widget.ImageCompress;
import com.itboye.eweilisten.util.widget.IsStringSPUtils;
import com.itboye.eweilisten.util.widget.MyListView;
import com.itboye.eweilisten.util.widget.PopupWindows;
import com.itboye.eweilisten.util.widget.SexDialogs;
import com.itboye.eweilisten.util.widget.XImageLoader;
import com.itboye.eweilisten.volley.ResultEntity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

/**
 * 个人中心
 */
public class PersonalDataActivity extends BaseActivity implements AddressFragment.GetInforListener, Observer, GirlGridAdapter.OnGridview {
    private RelativeLayout RelativeClass;//年级
    private RelativeLayout relaRegion;//地区
    private TextView tvPresonalRegion;//地区
    private TextView tvPresonalSex;
    private EditText tvPresonalNickName;
    private String nickName;
    private RelativeLayout relatSex;//性别
    private RelativeLayout user_name_layout;//呢称
    private SelectAddressDialog dialog;
    private TextView tvSystemHead;//系统头像
    private TextView userID;

    private String grade;//年级
    private String Sex;//性别
    private TextView tvPresonalClass;//学生
    private String School, SchoolId;//学校
    private EditText tvPresonalSchool;
    private TextView tvTitle;//标题
    private ImageView back;//返回
    private String provincename;//省份名称
    private String cityname;//城市名称
    private String districtname;//地区名称
    private String provinceno;//省份ID
    private String cityno;//城市ID
    private String districtno;//地区ID
    private RelativeLayout relayoutSchool;//小小
    private UserPresenter presenter;
    String name = null;
    PopupWindow popupWindow;
    MyListView list_history;
    private String nameOPe;
    ListView guigeContainer;
    OldAdapter oldAdapter;
    Dialog dialogs;

    EditText dialog_et;
    private ArrayList<AddressBean> arrayList = new ArrayList<>();
    private QuestionBean quelsit = new QuestionBean();
    private XueXiaoAdapter adapter;
    private XueShengAdapter Xuewadapter;

    private String xuewaStr, xuewaStrId;
    public static GirlGridAdapter grdaAdapter;
    private HeadGridAdapter headaAdapter;
    private CircleImageView imgHead;
    private String head;
    String Andress;
    private CameraPopupWindow cameraPopupWindow;
    // 使用相机拍照
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 110;
    // 获取日期格式器对象

    private String picture_name;
    private String fileName;
    private String localSelectPath;
    public static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择

    private String uid, auth_code;

    private TextView tvTest;//保存信息
    private String time;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_personal);
        relatSex = (RelativeLayout) findViewById(R.id.relatSex);
        tvPresonalNickName=(EditText)findViewById(R.id.tvPresonalNickName);
        tvTitle.setText("个人信息");
        tvTest.setText("保存");
        init();
        auth_code = (String) SPUtils.get(PersonalDataActivity.this, null,
                Const.AUTO_CODE, "");
        uid = (String) SPUtils.get(PersonalDataActivity.this, null,
                Const.ID, "");
        userID=(TextView)findViewById(R.id.tv_userID);
        userID.setText(uid);
        presenter = new UserPresenter(this);
    }

    public void init() {
        time = String.valueOf((int) (Math.random() * 10));
        grade = (String) SPUtils.get(MyApplication.instance, null,
                Const.READE_NAME, "");
        Sex = (String) SPUtils.get(MyApplication.instance, null,
                Const.SEX, "");
        School = (String) SPUtils.get(MyApplication.instance, null,
                Const.SCHOOL_NAME, "");

        head = (String) SPUtils.get(PersonalDataActivity.this, null,
                Const.HEAD, "");
        Andress = (String) SPUtils.get(PersonalDataActivity.this, null,
                Const.Andress, "");

        nickName = (String) SPUtils.get(PersonalDataActivity.this, null,
                Const.NICK, "");
        if (nickName == null || nickName.equals("")) {
            tvPresonalNickName.setText("");
        } else {
            tvPresonalNickName.setText(nickName);
        }
        if (Andress == null || Andress.equals("")) {
            tvPresonalRegion.setText("");
        } else {
            tvPresonalRegion.setText(Andress + "");
        }
        if (head == null || head.equals("")) {
            imgHead.setImageResource(R.drawable.logo_one);
        } else {
            String time = String.valueOf((int) (Math.random() * 10));
            Log.d("headheadhead", head);
            XImageLoader.load(Const.IMAGE_HEAD + head + "&random" + time, imgHead);
        }
        if (Sex == null || Sex.equals("")) {
            tvPresonalSex.setText("");
        } else if (Sex.equals("1")) {
            tvPresonalSex.setText("男");
        } else {
            tvPresonalSex.setText("女");
        }

        tvPresonalClass.setText(grade);
        tvPresonalSchool.setText(School);
        isCameraPermission(this, 1);
        showExtraDialog();

    }

    //6.0添加拍照的权限
    private static String[] PERMISSIONS_CAMERA_AND_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};

    public static boolean isCameraPermission(Activity context, int requestCode) {
        if (Build.VERSION.SDK_INT >= 23) {
            int storagePermission = ContextCompat.checkSelfPermission(context,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int cameraPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
            if (storagePermission != PackageManager.PERMISSION_GRANTED || cameraPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(context, PERMISSIONS_CAMERA_AND_STORAGE,
                        requestCode);
                return false;
            }
        }
        return true;
    }

    SexDialogs sexDialogs;
    HeadDialogs headDialogs;
    int position;

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.tvTest:
                showProgressDialog("保存中..", true);
                //  FilterUtil.onUserPresenter(presenter,auth_code,uid,nickName,Sex,nameOPe,xuewaStrId,SchoolId,Andress);
                //  SPUtils.put(PersonalDataActivity.this, null,Const.SCHOOL_NAME, School+"");
                FilterUtil.onUserPresenter(presenter, auth_code, uid,tvPresonalNickName.getText().toString().trim() , Sex, nameOPe, xuewaStrId, tvPresonalSchool.getText().toString().trim(), Andress);
                SPUtils.put(PersonalDataActivity.this, null, Const.SCHOOL_NAME, tvPresonalSchool.getText().toString().trim() + "");
                break;
            case R.id.user_name_layout:
                dialogs.show();
                break;
            case R.id.imgHead:
                cameraPopupWindow = new CameraPopupWindow(
                        PersonalDataActivity.this, onclicklister);
                cameraPopupWindow.showAtLocation(view, Gravity.BOTTOM
                        | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
            case R.id.tvSystemHead:
                presenter.onHeadQuestion(IsStringSPUtils.IsUid(),IsStringSPUtils.getSid());
                showProgressDialog("获取中...", true);
                HeadView(view);
                break;
            case R.id.RelativeClass:
                XuewShwng(view);
                presenter.onQuestion(IsStringSPUtils.IsUid(),IsStringSPUtils.getSid());
                showProgressDialog("获取中...", true);
                break;
            case R.id.relaRegion:
                AddressFragment addressFragment = new AddressFragment();
                addressFragment.show(getFragmentManager(), "addressfragment");
                break;
            case R.id.relatSex:
                SexView(view);
                break;
            case R.id.relayoutSchool://学校
//                if (districtno == null || districtno.equals("")) {
//                    AddressFragment address = new AddressFragment();
//                    address.show(getFragmentManager(), "address");
//                } else {
//                    Log.d("address", districtno);
//                    presenter.onSchool(districtno);
//                    showProgressDialog("获取中...", true);
//                    refreshQuery(view);
//                }
                break;

        }
    }

    /**
     * 自定义Dialog
     */
    private void showExtraDialog() {
        dialogs = new Dialog(PersonalDataActivity.this, R.style.rel_dialog);
        View view = LayoutInflater.from(PersonalDataActivity.this).inflate(
                R.layout.user_shezhi, null);
        dialogs.setContentView(view);
        dialog_et = (EditText) view.findViewById(R.id.dialog_et);

        TextView user_title = (TextView) view.findViewById(R.id.user_title);
        user_title.setText("修改昵称");
        dialog_et.setText(nickName);

        TextView dialog_ok = (TextView) view.findViewById(R.id.dialog_ok);
        TextView dialog_quxiao = (TextView) view.findViewById(R.id.dialog_quxiao);
        dialogs.setCanceledOnTouchOutside(false);
        dialog_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                try {
                    nickName = dialog_et.getText().toString();
                    tvPresonalNickName.setText(nickName + "");
                    dialogs.dismiss();
                } catch (Exception e) {
                }


            }
        });
        dialog_quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialogs.dismiss();
            }
        });
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        // 屏幕宽度
        int screenWidth = display.getWidth();
        // 屏幕高度
        int screenHeight = display.getHeight();
        Window window = dialogs.getWindow();

        WindowManager.LayoutParams lp = window.getAttributes();
        window.setGravity(Gravity.CENTER);
        lp.width = screenWidth * 3 / 4;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);

    }

    /**
     * 学校
     *
     * @param v
     */
    List<OldBean> old = new ArrayList<>();

    private void SexView(View v) {

        String sex[] = {"女", "男"};

        View views = View.inflate(MyApplication.instance, R.layout.dialog_xuexiao, null);
        list_history = (MyListView) views.findViewById(R.id.guigeContainer);
        TextView okchongzhi = (TextView) views.findViewById(R.id.okchongzhi);
        TextView ok = (TextView) views.findViewById(R.id.ok);
        TextView tvdialogTitle = (TextView) views.findViewById(R.id.tvdialogTitle);
        tvdialogTitle.setText("请选择性别");
        popupWindow = new PopupWindows(MyApplication.instance, v, views);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        list_history = (MyListView) views.findViewById(R.id.guigeContainer);
        popupWindow.setContentView(views);
        old.clear();
        for (int i = 0; i < sex.length; i++) {
            OldBean data = new OldBean();
            data.setName(sex[i]);
            old.add(data);

        }
        oldAdapter = new OldAdapter(PersonalDataActivity.this, old);
        list_history.setAdapter(oldAdapter);
        list_history.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                oldAdapter.clearSelection(position);
                oldAdapter.notifyDataSetChanged();
                Sex = old.get(position).getName();
            }
        });
        okchongzhi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (Sex == null || Sex.equals("")) {
                        MAlert.alert("还未选择");
                    } else {
                        Log.d("SexSex", Sex);
                        if (Sex.equals("0")) {
                            tvPresonalSex.setText("女");
                        } else if (Sex.equals("1")) {
                            tvPresonalSex.setText("男");
                        } else {
                            tvPresonalSex.setText(Sex);
                        }
                        popupWindow.dismiss();
                    }

                } catch (Exception e) {
                }


            }
        });
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();


            }
        });

    }


    /**
     * 学校
     *
     * @param v
     */
    private void refreshQuery(View v) {
        View views = View.inflate(MyApplication.instance, R.layout.dialog_xuexiao, null);
        list_history = (MyListView) views.findViewById(R.id.guigeContainer);
        TextView okchongzhi = (TextView) views.findViewById(R.id.okchongzhi);
        TextView ok = (TextView) views.findViewById(R.id.ok);
        popupWindow = new PopupWindows(MyApplication.instance, v, views);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        list_history = (MyListView) views.findViewById(R.id.guigeContainer);
        popupWindow.setContentView(views);
        arrayList = new ArrayList<>();
        list_history.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                School = arrayList.get(position).getName();
                SchoolId = arrayList.get(position).getId();
                adapter.getPositon(position);
                adapter.notifyDataSetChanged();
            }
        });
        okchongzhi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                try {
                    if (School == null) {

                    } else {
                        tvPresonalSchool.setText(School);
                    }
                } catch (Exception e) {
                }

            }
        });
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

            }
        });


    }

    /***
     * 年级
     * @param v
     */
    private void XuewShwng(View v) {

        View views = View.inflate(MyApplication.instance, R.layout.dialog_xuexiao, null);
        list_history = (MyListView) views.findViewById(R.id.guigeContainer);
        TextView okchongzhi = (TextView) views.findViewById(R.id.okchongzhi);
        TextView ok = (TextView) views.findViewById(R.id.ok);
        popupWindow = new PopupWindows(MyApplication.instance, v, views);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        list_history = (MyListView) views.findViewById(R.id.guigeContainer);
        popupWindow.setContentView(views);
        list_history.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    Xuewadapter.getPositon(position);
                    Xuewadapter.notifyDataSetChanged();
                    xuewaStr = quelsit.getGrade().get(position).getName();
                    xuewaStrId = quelsit.getGrade().get(position).getCode();
                } catch (Exception e) {
                }

            }
        });
        okchongzhi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                Log.d("namenamename", xuewaStr + "");
                try {
                    if (xuewaStr == null) {

                    } else {

                        tvPresonalClass.setText(xuewaStr);
                    }
                } catch (Exception e) {
                }

            }
        });
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

            }
        });

    }

    /**
     * 系统头像
     *
     * @param v
     */
    private void HeadView(View v) {
        View views = View.inflate(MyApplication.instance, R.layout.head_gridbview, null);
        guigeContainer = (ListView) views.findViewById(R.id.guigeContainer);
        TextView okchongzhi = (TextView) views.findViewById(R.id.okchongzhi);
        TextView okCancel = (TextView) views.findViewById(R.id.okCancel);

        popupWindow = new PopupWindows(MyApplication.instance, v, views);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setContentView(views);
        okCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        okchongzhi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                try {
                    if (nameOPe == null) {
                    } else {
                        XImageLoader.load(Const.IMAGE_HEAD + nameOPe, imgHead);
                        Intent intent = new Intent(FilterUtil.HEAD);
                        sendBroadcast(intent);
                    }
                } catch (Exception e) {
                }
            }
        });

    }

    /**
     * 地区选择
     */
    @Override
    public void onGetinforListener(String province, String city, String district, String provinceNo, String cityNo, String districtNo) {

        this.provincename = province;
        this.cityname = city;
        this.districtname = district;
        this.provinceno = provinceNo;
        this.cityno = cityNo;
        this.districtno = districtNo;
        if (city.equals("市辖区") | city.equals("县"))
            city = "";
        if (district.equals("市辖区"))
            district = "";
        System.out.println("nananannana" + province + " " + city + " " + cityno);
        Andress = province + " " + city + " " + district;

        if (Andress == null || Andress.equals("")) {
            tvPresonalRegion.setText("");
        } else {
            tvPresonalRegion.setText(Andress);
        }
    }


    @Override
    public void update(Observable o, Object arg) {

        ResultEntity entity = handlerError(arg);
        if (entity != null) {
            IsStringSPUtils.tianjia(entity);
            if (entity.getCode().equals("1111")) {
                Intent intent = new Intent(MyApplication.instance, LoginActivity.class);
                startActivity(intent);
                return;
            }
            if (entity.getEventType() == presenter.School_success) {
                arrayList = (ArrayList<AddressBean>) entity.getData();
                adapter = new XueXiaoAdapter(PersonalDataActivity.this, arrayList);
                list_history.setAdapter(adapter);
            }
            if (entity.getEventType() == presenter.Dtree_success) {
                quelsit = (QuestionBean) entity.getData();
                Xuewadapter = new XueShengAdapter(PersonalDataActivity.this, quelsit);
                list_history.setAdapter(Xuewadapter);
            }
            if (entity.getEventType() == presenter.HEAD_success) {
                quelsit = (QuestionBean) entity.getData();
                grdaAdapter = new GirlGridAdapter(PersonalDataActivity.this, quelsit);
                guigeContainer.setAdapter(grdaAdapter);
            }
            if (entity.getEventType() == presenter.Update_success) {
                MAlert.alert(entity.getData() + "");
                //  finish();
                presenter.onAutoLogin(IsStringSPUtils.IsUid(), IsStringSPUtils.getSid());
            }
            if (entity.getEventType() == presenter.ZiDong_success) {
                PersonDataBean personBean = (PersonDataBean) entity.getData();
                if (personBean != null) {
                    FilterUtil.putSharePre(PersonalDataActivity.this, personBean);
                    FilterUtil.sendLoginSucceed(this);
                }
            }
            try {
                closeProgressDialog();
            } catch (Exception e) {
            }

        }
    }

    @Override
    public void onBtn(String string) {
        Log.d("stringwaer", string);
        nameOPe = string;
    }

    private View.OnClickListener onclicklister = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // TODO Auto-generated method stub
            switch (view.getId()) {
                case R.id.open_camera:
                    /**
                     * 打开照相机
                     */
                    String state = Environment.getExternalStorageState();
                    if (state.equals(Environment.MEDIA_MOUNTED)) {
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(intent,
                                CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
                    } else {
                        MAlert.alert("请确认是否插入SD卡");
                    }
                    break;
                case R.id.pick_image:
                    // new PhotoSelectFragment(new PhotoSelect(),
                    // 6 - imgContainer.getChildCount() + 1).show(
                    // getSupportFragmentManager(), null);
                    // 激活系统图库，选择一张图片
                    Intent intent = new Intent(PersonalDataActivity.this, HeadPresActivity.class);
                    // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
                    startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                    break;

                default:
                    break;
            }
        }

    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE
                && resultCode == RESULT_OK) {
            String sdStatus = Environment.getExternalStorageState();
            if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
                return;
            }
            picture_name = android.text.format.DateFormat.format(
                    "yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
                    + ".jpg";
            Bundle bundle = data.getExtras();
            Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
            File file = new File("/sdcard/Image/");
            file.mkdirs();// 创建文件夹
            fileName = "/sdcard/Image/" + picture_name;
            FileOutputStream b = null;
            try {

                if (b == null) {

                    b = new FileOutputStream(fileName);
                    Log.d("fileOutputStreams", b + "");
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                    Log.d("fileOutputStream", b + "");
                    HeadUrl.onImage(fileName, imgHead);
                    Bitmap bm = BitmapFactory.decodeFile(fileName);
                    imgHead.setImageBitmap(bm);
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    b.flush();
                    b.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
//            UploadImage.getInstance().execute(fileName, this);
            cameraPopupWindow.dismiss();
        } else if (requestCode == PHOTO_REQUEST_GALLERY && resultCode == PHOTO_REQUEST_GALLERY) {
            localSelectPath = data.getStringExtra("path");
            /**
             * 当选择的图片不为空的话，在获取到图片的途径
             */
            localSelectPath = ImageCompress.compress(localSelectPath);
            Log.d("localSelectPathImas", localSelectPath + "");
            HeadUrl.onImage(localSelectPath, imgHead);
            cameraPopupWindow.dismiss();
        } else if (requestCode == IMAGE_COMPLETE) {
//            UploadImage.getInstance().execute(localSelectPath, this);
            cameraPopupWindow.dismiss();
        }
    }

    public static final int IMAGE_COMPLETE = 6; // 结果

    /**
     * This method is used to get real path of file from from uri<br/>
     * http://stackoverflow.com/questions/11591825/how-to-get-image-path-just-
     * captured-from-camera
     *
     * @param contentUri
     * @return String
     */
    public String getRealPathFromURI(Uri contentUri) {
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = this.managedQuery(contentUri, proj, null, null,
                    null);
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } catch (Exception e) {
            return contentUri.getPath();
        }
    }
}
